﻿/*
 * redmicro all Copyright (c)
 */

Rsd.define('Rsd.zen.page.ListPage', {
    extend: 'Rsd.container.Page',
    requires: [
        'Rsd.widget.ModelForm',
        'Rsd.control.Grid',
        'Rsd.control.SearchToolBar',
        'Rsd.control.PagingBar'
    ],
    xtype: 'base-block-list-page', 
    header:null,
    tabTitle: 'Title',
    layout: 'fit',
    selected:true,
    //toolBar:'search-tool-bar',
    //footBar:'paging-bar',
    gridHeaderVisible:true,
    items:[
        {
            xtype: 'grid', 
            name:'grid',
            autoScrollIntoView:true,
            toolBar:{xtype: 'search-tool-bar', height:'60px',width:'100%',style:{minHeight:50}},
            footBar:{xtype:'paging-bar',indexChanged:'pageIndexChanged'},
            rowdblclick: 'grid_row_dblclick',
            rowclick:''
        }
    ],
    /**
    * @description 点击显示数据
    */
    rowDblClick:'showItem', 
    /*
    * */
    //formFields:[], 
    //
    formSchema:null,
    /*
    * */
    //gridColumns:[], 
    /**
     * @description 优先级排第一
     * @description 获取数据源的 服务名 优先使用serviceName ,获取到的Service 将作为dataStore的proxy属性值
     */
    serviceName:null,
    /**
     * @description 优先级排第二
     * @description Rsd.data.Store数据源，支持本地数据已本地缓存数据
     * @description 在serviceName有效时，该属性将自动创建为 new Rsd.data.Store({proxy:app.getService(serviceName),listName:listMember})
     */
    dataStore:null,
    /**
     * @description 在serviceName有效时，listMember将作为dataStore的listName属性值
     */
    listMember:null,
    /*
    * */
    constructor: function ListPage(config) {
        config = config || {};
        this.apply(config);   
 
    }, 
    /**
     * 
     */
    onBeforeInit:function onBeforeInit()
    { 
          
        if(this.menu)
        {
            this.readonly = this.menu.readonly == undefined ? this.readonly : this.menu.readonly;
            this.modelType = this.modelType || this.menu.modelType;
            this.serviceName =  this.serviceName || this.menu.serviceName; 
            this.listMember = this.listMember || this.menu.listMember || 'rows';
            this.where = Rsd.arrayConcat(this.where || [],this.menu.where||[]);
            this.sort = Rsd.arrayConcat(this.sort || [],this.menu.sort||[]);

            //this.columns = this.columns || this.menu.columns || [];
            this.searchColumns = Rsd.arrayConcat(this.searchColumns ||[], this.menu.searchColumns||[]);
            this.newButtons = Rsd.arrayConcat(this.newButtons || [],this.menu.newButtons||[]); 

            this.titleField =  this.titleField || this.menu.titleField || '';
            this.titleMember = this.titleMember || this.menu.titleMember || '';
 
            if(this.menu.formTitle)
            {
                this.form.title = this.menu.formTitle;
            }
            if(this.menu.formModelType)
            {
                this.form.modelType = this.menu.formModelType;
            }

        }

        if(this.newButtons.find(item=>item.handler == '_btn_search' || item.fn == '_btn_search')===undefined)
        {
            this.newButtons.splice(0,0,{xtype:'button', text: '查 询' ,visible:true,margin: '0 5 0 10', width: 100, handler:'_btn_search'});
        }
      
        //4.* 版本下，监控；下一个版本取消
        if(Rsd["version"].startWith('4.'))
        {
            if(this.formViewType)
            {
                this.form.viewType = this.formViewType;
                console.error('formViewType属性已取消，请使用form:{viewType:"XXXX"}方式代替');
            }
            if(this.formModelType)
            {
                this.form.modelType = this.formModelType;
                console.error('formModelType属性已取消，请使用form:{modelType:"XXXX"}方式代替');
            }
            if(this.formTitle)
            {
                this.form.title = this.formTitle;
                console.error('formTitle属性已取消，请使用form:{title:"XXXX"}方式代替');
            }
            if(this.titleField)
            {
                this.form.titleField = this.titleField;
                console.error('titleField属性已取消，请使用form:{titleField:"XXXX"}方式代替');
            }
            if(this.formFieldWidth)
            {
                this.form.fieldWidth = this.formFieldWidth;
                console.error('formFieldWidth属性已取消，请使用form:{fieldWidth:"45%"}方式代替');
            } 
            if(this.formHeight)
            {
                this.form.height = this.formHeight;
                console.error('formHeight属性已取消，请使用form:{height:"XXXX"}方式代替');
            }
            if(this.formWidth)
            {
                this.form.width = this.formWidth;
                console.error('formWidth属性已取消，请使用form:{width:"XXXX"}方式代替');
            }
            if(this.formData)
            {
                this.form.data = this.formData;
                console.error('formData属性已取消，请使用form:{data:{}}方式代替');
            } 
            if(this.formPosition)
            {
                this.form.position = this.formPosition;
                console.error('formPosition属性已取消，请使用form:{position:"XXXX"}方式代替');
            }
            if(this.formButtons)
            {
                this.form.buttons = this.formButtons;
                console.error('formButtons属性已取消，请使用form:{buttons:[]}方式代替');
            }
        } 
         
        this.callParent(); 
         
    },
    /**
     * 
     */
    onAfterInit:function onAfterInit()
    {
        this.toolBar.newButtons = this.newButtons; 
        this.toolBar.searchColumns = this.searchColumns; 
        this.callParent(); 
        //console.log('lispage onBeforeInit',this.toolBar.onAfterInit.length, this.toolBar.searchColumns.length);
    },
    /*
     * */
    pageIndexChanged: function pageIndexChanged(pagingOpt) {
        //debugger;

        this.load({});//只需重新加载，pagingOpt 信息自动获取

    },
   
    /** 
     args :api 接口需要的参数
    *
    * */
    load:function load(args,callback) {      
        
        //debugger;
        
        var me = this;
        var grid = me.items[0];
        if(!(grid instanceof Rsd.control.Grid))
        {
            console.error("me.items[0] is not Rsd.control.Grid");
            return;
        }
        if(Rsd.isArray(args))
        { 
            //console.trace('list page load array',arguments);  
            this.callParentFn('load',[{'grid':args},callback]);
            //grid.loadData(args);
            return;
        }

        if(!me.dataStore)
        {
             var _serviceName = me.serviceName || (me.modelSchema && me.modelSchema.listService); 
            
            if(!Rsd.isEmpty(_serviceName))
            {  
                var _service = Rsd.app.getService(_serviceName);
                if(_service)
                {
                    me.dataStore = Rsd.create('Rsd.data.Store',{proxy:_service,listName:me.listMember ||'rows'}); 
                } 
            }
        }  
      
        if(me.dataStore)
        {
            grid.dataSource = me.dataStore;
        }  
        if(!grid.dataSource)
        {
            grid.dataSource =[];
            console.error('ListPage未设置属性serviceName');   
            return;
        }

        Rsd.showWaiting(me.id, grid); 
        
        setTimeout(function () {
          
            var opt  = me.getPagingOpt();
            var _args = Rsd.apply(args||{}, {
                modelType: me.modelType || '',
                pageSize: opt.pageSize || 100,
                pageIndex: opt.pageIndex || 0,
            });
            
            _args.where =  Rsd.arrayConcat(_args.where,me.where, me.toolBar && me.toolBar.getWhere()),
            _args.sort = Rsd.arrayConcat(_args.sort, me.sort);
            var _fn = function (resp) {

                if(resp && resp.success)
                {
                    var _data = resp.data||{};
                    if(Rsd.isArray(_data))
                    {
                        me.setPagingOpt({pageSize:opt.pageSize,pageIndex:0,pageCount:1,totalCount:_data.length});
                    }
                    else
                    {
                        me.setPagingOpt({pageSize:_data.pagesize||100,pageIndex:_data.pageindex||0,pageCount:_data.pagecount||0,totalCount:_data.total||0});
                    }
                }

                var _f = Rsd.callFunction(me, callback||function (__data) {

                    if(__data===undefined || __data === null)
                    {
                        Rsd.alert('数据加载失败', '未获取到数据（网络故障）。');
                        return false;
                    }
                    if(Rsd.isArray(__data))
                    {
                        return true;
                    }
                    if(__data.success)
                    {}
                    else
                    {

                        if(Rsd.isEmpty(__data.msg))
                        { 
                            console.error('未知错误(UI0009),请查看日志。',resp);
                        }
                       
                        return true;
                    }

                    return true;

                }, arguments);

                Rsd.closeWaiting(me.id);
                //console.log('BaseListPage.loadData return: ' + _f);
                return _f;
            };
 
            grid.loadData(_args,_fn);
            
        }, 50);

    },
    /**
    * 
    */
    _btn_search:function _btn_search() {

        //友好做法时：在查询条件发发生改变时，设置分页 {pageIndex: 0}
        if(this.whereIsChange())
        {
            this.setPagingOpt({pageIndex:0});
        }
 
        this.load({});
    },
     
    /**
    * 
    * */
    whereIsChange:function whereIsChange() {

        var _where = this.toolBar&&this.toolBar.getWhere();
        if (Rsd.isEmpty(this.____lastWhere) && Rsd.isEmpty(_where)) {
            return false;
        }
        if (Rsd.isEmpty(this.____lastWhere) || !Rsd.isEmpty(_where)) {
            return true;
        }
        if (!Rsd.isEmpty(this.____lastWhere) || Rsd.isEmpty(_where)) {
            return true;
        }
        if (this.____lastWhere.length  != _where.length) {
            return true;
        }
        for(var i in _where)
        {

        }
        return true;
    },

    /**
    * @description 获取分页信息,在查询时，自动加上分页信息
    * */
    getPagingOpt:function getPagingOpt() {
      if(this.items[0].footBar instanceof  Rsd.control.PagingBar)
      {
          return this.items[0].footBar.getPaging();
      }
      return {pageIndex:0,pageSize:1000};
    },

    /**
    * @description 设置分页信息,一般在查询条件发发生改变时，需重新设置分页 {pageIndex: 0}
    * */
    setPagingOpt:function setPagingOpt(opt) {

        if(this.items[0].footBar instanceof  Rsd.control.PagingBar)
        {
            return this.items[0].footBar.setPaging(opt);
        }
    },
   
    /**
    *  @description 获取表格的数据
     * */
    getListData:function getListData()
    {
        var grid = this.items[0];
        return grid.rows;
    },
    /*
    * */
    grid_row_dblclick:function grid_row_dblclick(row,evt,data)
    {
        //data['readonly'] = this.readonly;
        this.funApplyByIOC(this.rowDblClick,[row,evt,data]);
    },
    /**
     * 
     * @param {*} row 
     * @param {*} readonly 
     * @returns 
     */
    createFormDialog:function createFormDialog(row,readonly)
    {
        var _schema = this.formSchema||this.modelSchema;
         
        var _form = this.form;  //form 配置项
        var _title = "";
        //优先使用 formTitle
        var _tplStr =  this.form.title||null;
        if(Rsd.isEmpty(_tplStr))
        {  
            var _titleField = _form.titleField|| this.titleMember || (_schema&&_schema.titleField);
            _tplStr =  ( _tplStr ||'详细信息') + "-[{{=("+_titleField+"||\'*\')}}]";
        }
        if(_tplStr)
        {
            try
            { 
                _title = Rsd.template(_tplStr,row||{}); 
            }
            catch(err)
            {
                _title = _tplStr;
                console.error(err);
            }
        } 
        else
        {
            _title = "详细信息(未设置formTitle)";
        }
        
        var _height = _form.height||(500+120);
        var _width = _form.width||(680+100);
        
        var _buttons = _form.buttons;
        
        //console.log(_buttons);
        var _viewType = _form.viewType||'Rsd.zen.dialog.FormDialog';
        var _fields = this.formFields||[]; 
        if(_fields.length==0)
        {
            _fields = _form.fields||[]; 
        }
        if(_fields.length==0)
        {
            _fields = _schema.fields||[];
        }
        
        return Rsd.create(_viewType, {
            title: _title||_tplStr,
            formHeight:'auto',
            formFields:_fields, 
            fieldWidth:this.form.fieldWidth||'45%',
            modelSchema:_schema,
            modelType:this.form.modelType, 
            parent:this,
            readonly:readonly,
            buttons:_buttons,
            height:_height,
            width:_width,
            data:row, 
        });
 
    },
    /**
     *  @description 展示row数据
     */
    showItem:function showItem(row,evt,data)
     {
        var readonly = this.readonly;//data['readonly'];
         var form = this.createFormDialog(row,readonly); 
         
         switch (this.form.position) {

            case "left":
                form.showDialogOnLeft();
                break;
            case "right":
                form.showDialogOnRight();
                break;
            default:
                form.showDialog();
                break;
        } 
     },
    /** 
    * @private
    * */
    buildGridColumns:function buildGridColumns() {
        var me = this;
        var _cols = [];
        Array.prototype.push.apply(_cols, this.gridColumns||[]);
        Array.prototype.push.apply(_cols, this.opColumns||[])

        //为列自动关联format方法
        for(var i in _cols)
        {
            var c = _cols[i]; 
            if(!c || c.format)
            {
                continue;
            }
            if(this['format'+c.name])
            {
                c.format = 'format' + c.name; 
            }
        }

        var grid = this.items[0];
        if(grid instanceof Rsd.control.Grid)
        {
            grid.buildColumns(_cols);
            return;
        }
      
        if(grid instanceof  Object)
        {
            grid.columns = _cols;
        }
    },
    /**
     * 本地表格数据导出excel
     * @param {*} sheet 
     * @param {*} file 仅文件名称（不是路径）
     */
    "export": function _export(sheet,file) {
        var grid = this.items[0];
        grid.export(sheet,file);
    }


},function(type){

    //formFields
    var _formFieldsGetter = function () {
        if(this.__formFields == undefined)
        {
            this.__formFields = [];
        }
        return this.__formFields;
    };

    var _formFieldsSetter = function (value) {
        this.__formFields = value;
    }

    this.defineProperty(type,"formFields", _formFieldsGetter, _formFieldsSetter,true);

    
    //gridColumns
    var _columnsGetter = function () {
        if(this.__gridColumns == undefined)
        {
            this.__gridColumns = [];
        }
        return this.__gridColumns;
    };

    var _columnsSetter = function (value) {
        this.__gridColumns = value;

        this.buildGridColumns();
    }

    this.defineProperty(type,"gridColumns", _columnsGetter, _columnsSetter,true);
    
    //opColumns
    var _opColumnsGetter = function () {

        return this.__opColumns||[];
    };

    var _opColumnsSetter = function (value) {

        this.__opColumns = value;
        this.buildGridColumns();
    }

    this.defineProperty(type,"opColumns", _opColumnsGetter, _opColumnsSetter,true);
 
     
    //newButtons
    var _newButtonsGetter = function () {
       
        if(!this.hasOwnProperty('__newButtons'))
        {
            this.__newButtons = [];
        }
        
        return this.__newButtons;
    };

    var _newButtonsSetter = function (value) {
        var _value = value||[];  
        for(var i in _value)
        {
            if(Rsd.isObject(_value[i]))
            {
                if(Rsd.isEmpty(_value[i].margin))
                {
                    _value[i].margin = '0 5 0 10';
                } 
            }
           
        }
        if(_value == this.__newButtons)
        {
            return;
        }
        this.__newButtons = _value; 
    }

    this.defineProperty(type,"newButtons", _newButtonsGetter, _newButtonsSetter,true);

    //searchColumns
    var _searchColumnsGetter = function _searchColumnsGetter() { 
         
        if(!this.__searchColumns)
        {
            this.__searchColumns = [] ;
        }

        return this.__searchColumns;
    }

    var _searchColumnsSetter = function _searchColumnsSetter(value) { 
            
        this.__searchColumns = value||[]; 
     }

    this.defineProperty(type,"searchColumns", _searchColumnsGetter, _searchColumnsSetter,true);

    //toolBar
    var _toolBarGetter = function _toolBarGetter() {

        if(this.items.length ==0)
        {
            return null;            
        }
        if(this.items[0].toolBar && this.items[0].toolBar.content instanceof  Rsd.common.ComponentX)
        {
            return this.items[0].toolBar.content;
        }
        return this.items[0].toolBar;
    };

    var _toolBarSetter = function _toolBarSetter(value) {

        if(Rsd.isString(value))
        {
            this.items[0].toolBar.xtype = value;
            return;
        }

        if(Rsd.isObject(value) ) {
            Rsd.apply(this.items[0].toolBar, value);
            return;
        }

        this.items[0].toolBar = value;
    }
  
    this.defineProperty(type,"toolBar", _toolBarGetter, _toolBarSetter,false);

    //footBar
    var _footBarGetter = function _footBarGetter() {

        return this.items[0].footBar;
    };

    var _footBarSetter = function _footBarSetter(value) {

        if(Rsd.isString(value))
        {
            this.items[0].footBar.xtype = value;
            return;
        } 
        if(Rsd.isObject(value))
        {
            Rsd.apply(this.items[0].footBar, value); 
            return;
        }
        this.items[0].footBar = value;
    }

    this.defineProperty(type,"footBar", _footBarGetter, _footBarSetter,false);

    //
    var _formGetter = function _formGetter()
    {
        if(Rsd.isEmpty(this.__form))
        {
            this.__form = {
                viewType:'Rsd.zen.dialog.FormDialog',//明细窗体类型
                modelType:this.modelType,
                fields:null,
                fieldWidth:'45%',//form 字段默认宽度
                titleField:'',
                title:'',
                height:'auto',//form 窗体高度
                width:'60%', //form 窗体宽度
                position:'center', //表单展示位置 center,left,right  
                buttons:['save','delete','cancel'],//form 表单底部buttons
                data:{}//新增时 form默认数据 
            };
        }

       return this.__form;
    };

    var _formSetter  =function _formSetter(value)
    {
        if(Rsd.isString(value))
        {
            this.form.viewType = value;
            return;
        }
       
        if(Rsd.isObject(value))
        {
            Rsd.apply(this.form,value);
            return;
        }
        
    }

    this.defineProperty(type,"form", _formGetter, _formSetter,true);
});